package com.aqielife.demo.config;

import org.springframework.amqp.core.*;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

import static com.aqielife.demo.MQConstant.*;


/**
 * @author aqie
 * @date 2022/02/06 16:48
 * @desc
 */
@SpringBootConfiguration
public class RabbitmqConfig {

  /**
   * 1. 工作模型队列
   * @return
   */
  @Bean
  public Queue queueWork() {
    return new Queue(QUEUE_WORK);
  }

  /**
   * 2. 发布订阅模型
   * @return
   */
  @Bean
  public Queue queueFanout() {
    return new Queue(QUEUE_FANOUT);
  }

  // 准备一个交换机
  @Bean
  public FanoutExchange exchangeFanout() {
    return new FanoutExchange(EXCHANGE_FANOUT);
  }

  // 将交换机和队列进行绑定 可以绑定多个queue
  @Bean
  public Binding bindingExchange() {
    return BindingBuilder.bind(queueFanout()).to(exchangeFanout());
  }


  /**
   * 3. topic 模型
   * @return
   */
  @Bean
  public Queue queueTopicMusic() {
    return new Queue(QUEUE_TOPIC_MUSIC);
  }

  @Bean
  public Queue queueTopicSport() {
    return new Queue(QUEUE_TOPIC_SPORT);
  }

  @Bean
  public TopicExchange exchangeTopic() {
    return new TopicExchange(EXCHANGE_TOPIC);
  }

  @Bean
  public Binding bindingTopicMusic() {
    return BindingBuilder.bind(queueTopicMusic()).to(exchangeTopic()).with(ROUTING_KEY_1);
  }

  @Bean
  public Binding bindingTopicSport() {
    return BindingBuilder.bind(queueTopicSport()).to(exchangeTopic()).with(ROUTING_KEY_2);
  }

  /**
   * 4. TTL 队列
   */
  @Bean
  public Queue queueTTL() {
    Map<String, Object> map = new HashMap<>(1);
    map.put("x-message-ttl", 10000);
    return new Queue(QUEUE_TTL, true, false, false, map);
  }


  /**
   * 5. 死信队列
   */
  // 产生死信的队列
  @Bean
  public Queue queueDLX() {
    Map<String, Object> map = new HashMap<>(2);
    // 5秒后，消息自动变为死信
    map.put("x-message-ttl", 5000);
    map.put("x-dead-letter-exchange", "exchange_receive");
    map.put("x-dead-letter-routing-key", "receive_key");
    return new Queue("queue_dlx", true, false, false, map);
  }
  // 死信交换机
  @Bean
  public DirectExchange exchangeDLX() {
    return new DirectExchange("exchange_dlx");
  }
  // 给死信队列绑定交换机
  @Bean
  public Binding bindingDLX() {
    return BindingBuilder.bind(queueDLX()).to(exchangeDLX()).with("receive_key");
  }
  // 死信接收交换机
  @Bean
  public DirectExchange exchangeReceive() {
    return new DirectExchange("exchange_receive");
  }
  // 接收死信的队列
  @Bean
  public Queue queueReceive() {
    return new Queue("queue_receive");
  }
  // 将交换机与队列绑定
  @Bean
  public Binding bindingReceive() {
    return BindingBuilder.bind(queueReceive()).to(exchangeReceive()).with("receive_key");
  }

}
